#!/usr/bin/env python3

import os
import os.path
import shutil
import glob
from itertools import count

def load_trans(trans_path):
    COMMENT, EN, JA = "#", "en:", "ja:"
    trans_dict = {}
    en = None
    with open(trans_path) as f:
        for lineno, line in zip(count(1), f):
            if line.startswith(COMMENT):
                pass
            elif line.startswith(EN):
                en = line[len(EN):].rstrip()
            elif line.startswith(JA):
                if not en:
                    raise IOError("invalid en-ja pair found at line "
                            + str(lineno))
                trans_dict[en] = line[len(JA):].rstrip()
                en = None
            else:
                if len(line.rstrip()):
                    raise IOError("invalid line found at line "
                            + str(lineno))
    return trans_dict


def translate(trans_path, src_path, dst_path):
    print("generating", dst_path, "...")

    trans_dict = load_trans(trans_path)
    trans_dict.update(load_trans("trans/common.trans"))

    with open(src_path, encoding="utf-8") as srcf:
        with open(dst_path, mode="w", encoding="utf-8") as dstf:
            for line in srcf:
                en = line.rstrip()
                if en in trans_dict:
                    print(trans_dict[en], file=dstf)
                else:
                    print(en, file=dstf)


if __name__ == "__main__":
    if os.path.exists("output"):
        shutil.rmtree("output")
    os.makedirs("output")

    for src_path in glob.glob("original/*.html"):
        dirs, filename = os.path.split(src_path)
        trans_path = os.path.join("trans", filename + ".trans")
        if os.path.exists(trans_path):
            dst_path = os.path.join("output", filename)
            translate(trans_path, src_path, dst_path)

